/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-08-08 17:56:35
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-08-13 18:11:56
 * @FilePath: /lesson43/TcpServer.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include "Log.hpp"
#include "Socket.hpp"
#include <signal.h>
#include <functional>
#include <string>

using namespace std;

using func_t = function<string(string &)>; // Calculator

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback) : port_(port), callback_(callback)
    {
    }
    bool InitServer()
    {
        listensock_.Socket();
        listensock_.Bind(port_);
        listensock_.Listen();
        lg(Info, "Init server ... done");
        return true;
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (1)
        {
            string clientip;
            uint16_t clientport;
            int sockfd = listensock_.Accept(&clientip, &clientport);
            if (sockfd < 0)
                continue;
            lg(Info, "Accept a new link,sockfd:%d,clientip:%s,clientport:%d", sockfd, clientip.c_str(), clientport);
            // 提供服务
            if (fork() == 0)
            {
                listensock_.Close();
                string str_stream;
                // 数据计算
                while (1)
                {
                    char inbuffer[1280];
                    ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer));
                    if (n > 0)
                    {
                        inbuffer[n] = 0;
                        str_stream += inbuffer;

                        lg(Debug, "Debug: \n%s", str_stream.c_str());

                        while (1)
                        {
                            string info = callback_(str_stream);
                            if (info.empty())
                                break;
                            lg(Debug, "Debug,Info:\n%s", info.c_str());
                            lg(Debug, "Debug,inbuffer_stream:\n%s", str_stream.c_str());

                            write(sockfd, info.c_str(), info.size());
                        }
                    }
                    else if (n == 0)
                    {
                        break;
                    }
                    else
                    {
                        break;
                    }
                }

                exit(0);
            }
            close(sockfd);
        }
    }
    ~TcpServer() {}

private:
    uint16_t port_;
    Sock listensock_;
    func_t callback_;
};
